package com.flight.trans.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentTransaction;

import com.flight.trans.R;
import com.flight.trans.adapter.MainDrawableAdapter;
import com.flight.trans.bean.MessageSocketBean;
import com.flight.trans.bean.RouterBean.RouterData;
import com.flight.trans.bean.RouterBean.RouterData.RouterChildren;
import com.flight.trans.bean.UpdateBean.UpdateData;
import com.flight.trans.bean.UserBean;
import com.flight.trans.fragment.EnterPortPickingFragment;
import com.flight.trans.fragment.EnterPortTakeFragment;
import com.flight.trans.fragment.EnterPortWarehousingFragment;
import com.flight.trans.fragment.LeavePortCollectCheckFragment;
import com.flight.trans.fragment.LeavePortGroupBoardFragment;
import com.flight.trans.fragment.LeavePortReturnFragment;
import com.flight.trans.fragment.LeavePortWarehousingFragment;
import com.flight.trans.fragment.LeavePortDuplicateFragment;
import com.flight.trans.fragment.LeavePortWeighingFragment;
import com.flight.trans.fragment.StoreroomInventoryFragment;
import com.flight.trans.fragment.WriteNFCFragment;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.listener.MainDrawerListener;
import com.flight.trans.receiver.NetPowerBroadcastReceiver;
import com.flight.trans.service.MessageService;
import com.flight.trans.service.RefreshService;
import com.flight.trans.util.LogUtils;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.MessageDialog;
import com.flight.trans.view.dialog.UpdateDialog;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.flight.trans.base.BaseActivity;
import com.flight.trans.base.BaseFragment;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.ProgressUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout mRlContainer ;
    private DrawerLayout mDlContainer ;
    private TextView mTvSectionName ,//部门名字
            mTvUserName ,//用户姓名
            mTvVersionName ;//版本名
    private ImageButton mIbVersionUpdate ;//升级

    private ExpandableListView mElvNavigation ;
    private MainDrawableAdapter mMainDrawableAdapter;
    private Intent mMessageService ,//消息服务
                mRefreshService;// 刷新服务

    private View mViewLeftLine ;

    private TextView mTvMessagePosition;
    private List<RouterData> mRouterDataList ;
    private BaseFragment baseFragment ;

    private int currentGroupPosition ;
    private String currentType = "";

    private UpdateData mUpdateData ;
    private boolean isShowMessageDialog = true;

    @Override
    protected int setContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        mRlContainer = findViewById(R.id.mRlContainer);
        mTvSectionName = findViewById(R.id.mTvSectionName);
        mTvUserName = findViewById(R.id.mTvUserName);
        mDlContainer = findViewById(R.id.mDlContainer);
        mTvVersionName = findViewById(R.id.mTvVersionName);
        mIbVersionUpdate = findViewById(R.id.mIbVersionUpdate);
        mViewLeftLine = findViewById(R.id.mViewLeftLine);

        mElvNavigation = findViewById(R.id.mElvNavigation);
        mTvMessagePosition = findViewById(R.id.mTvMessagePosition);

        mViewLeftLine.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mDlContainer.openDrawer(GravityCompat.START);
                return false;
            }
        });
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void initData() {
        // 版本号
        mTvVersionName.setText(CommonUtils.getVersionName(mActivity));

        // 监听抽屉内容打开关闭
        mElvNavigation.setOnGroupExpandListener(new GroupExpandListener());
        // 监听抽屉
        mDlContainer.addDrawerListener(mDrawerListener);

        CommonUtils.setScreenContainerPaddingTop(mRlContainer);
        CommonUtils.getPermissions(mActivity);

        mRefreshService = new Intent(mActivity , RefreshService.class);
        startService(mRefreshService);

        // 删除日志
        CommonUtils.deleteLog(Constant.Net_File_Path);
        CommonUtils.deleteLog(Constant.Crash_File_Path);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(new NetPowerBroadcastReceiver(mActivity), filter);

        if(Constant.MODEL_M5.equals(Build.MODEL))
            initM5Optics();
    }

    @Override
    protected void initConnect() {
        // 获取用户信息
        NetworkUtils.getUerInfo(new OkGoBackListener(mActivity){
            @Override
            public void onSuccess(Object body) {
                UserBean userBean = (UserBean) body;
                mTvSectionName.setText(userBean.getUser().getDept().getDeptName());
                mTvUserName.setText(userBean.getUser().getNickName());

                ConstantInfo.mPermissionsList = userBean.getPermissions();

                int userId = userBean.getUser().getUserId();

                String roleIds = "" ;
                for (int i = 0; i < userBean.getUser().getRoles().size(); i++) {
                    roleIds += userBean.getUser().getRoles().get(i).getRoleId() + "_";
                }

                ConstantInfo.IS_ADMIN = userBean.getRoles().contains("admin");

                ConstantInfo.SOCKET_KEY = roleIds + "@" + userId + "@" + ConstantInfo.TOKEN;

                // 开启消息服务
                mMessageService = new Intent(mActivity , MessageService.class);
                startService(mMessageService);
            }
        });

        // 获取菜单信息
        NetworkUtils.getRouters(new OkGoBackListener(mActivity){
            @Override
            public void onSuccess(Object body) {
                List<RouterData> routerDataList = (List<RouterData>) body;

                mRouterDataList = new ArrayList<>();

                if(routerDataList != null)
                    for (int i = 0; i < routerDataList.size(); i++) {
                        if(Constant.JGBZ.equals(routerDataList.get(i).getPath())
                                || Constant.CGBZ.equals(routerDataList.get(i).getPath())
                                || Constant.YHGL.equals(routerDataList.get(i).getPath())){
                            mRouterDataList.add(routerDataList.get(i));
                        }
                    }

                initNavigationContainer();
            }
        });

        NetworkUtils.checkUpdate(new OkGoBackListener(mActivity){
            @Override
            public void onSuccess(Object body) {
                mUpdateData = (UpdateData) body;

                if(mUpdateData.getVersion() > CommonUtils.getVersionCode(mActivity)){
                    mIbVersionUpdate.setVisibility(View.VISIBLE);

                    showUpdateShow();
                }else {
                    mIbVersionUpdate.setVisibility(View.GONE);
                }
            }
        });
    }

    private void showUpdateShow(){
        UpdateDialog.getInstance(mActivity)
                .builder(mUpdateData)
                .show();
    }

    /**
     * 监听抽屉内容打开关闭
     */
    private class GroupExpandListener implements ExpandableListView.OnGroupExpandListener{
        @Override
        public void onGroupExpand(int groupPosition) {
            if(mRouterDataList == null || mRouterDataList.get(groupPosition) == null)
                return;

            if(currentGroupPosition != groupPosition && mElvNavigation.isGroupExpanded(currentGroupPosition)) {
                mElvNavigation.collapseGroup(currentGroupPosition);
            }
            currentGroupPosition = groupPosition;
        }
    }

    private void initNavigationContainer() {
        mMainDrawableAdapter = new MainDrawableAdapter(mActivity , mRouterDataList);
        mElvNavigation.setAdapter(mMainDrawableAdapter);

        mMainDrawableAdapter.setOnItemClickListener(new MainDrawableAdapter.OnItemClickListener() {
            @Override
            public void onClick(int groupPosition ,int childPosition) {
                mDlContainer.closeDrawers();

                if(mRouterDataList == null || mRouterDataList.get(groupPosition) == null)
                    return;

                RouterChildren routerChildren = mRouterDataList.get(groupPosition).getChildren().get(childPosition);

                if(!TextUtils.isEmpty(currentType) && currentType.equals(routerChildren.getComponent()))
                    return;

                currentType = routerChildren.getComponent();

                switch (currentType){
                    case Constant.JGRK:
                        // 进港入库
                        changeFragment(new EnterPortWarehousingFragment());
                        break;
                    case Constant.JGCK:
                        // 进港出库
                        changeFragment(new EnterPortPickingFragment());
                        break;
                    case Constant.JGTH:
                        // 进港提货
                        changeFragment(new EnterPortTakeFragment());
                        break;
                    case Constant.JGPK:
                        // 进港盘库
                        changeFragment(new StoreroomInventoryFragment(0));
                        break;
                    case Constant.SYHC:
                        // 出港收运核查
                        changeFragment(new LeavePortCollectCheckFragment());
                        break;
                    case Constant.CGRK:
                        // 出港入库
                        changeFragment(new LeavePortWarehousingFragment());
                        break;
                    case Constant.CGZB:
                        // 出港组板
                        changeFragment(new LeavePortGroupBoardFragment());
                        break;
                    case Constant.CGFZ:
                        // 出港复重
                        changeFragment(new LeavePortDuplicateFragment());
                        break;
                    case Constant.CGTY:
                        // 出港退运
                        changeFragment(new LeavePortReturnFragment());
                        break;
                    case Constant.CGPK:
                        // 出港盘库
                        changeFragment(new StoreroomInventoryFragment(1));
                        break;
                    case Constant.CGCZ:
                        // 出港称重
                        changeFragment(new LeavePortWeighingFragment());
                        break;
                    case Constant.BQXR :
                        // 标签写入
                        changeFragment(new WriteNFCFragment());
                        break;
                    case Constant.TCDL:
                        // 退出账号
                        AlertDialog.getInstance(mActivity)
                                .setContentResource(R.string.dialog_user_login_out)
                                .setConfirmButton(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        NetworkUtils.logOut(new OkGoBackListener(mActivity){
                                            @Override
                                            public void onSuccess(Object body) {
                                                onFinishAct(LoginActivity.class);
                                            }
                                        });
                                    }
                                }).setCancelButton(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        currentType = "";
                                    }
                                }).show();
                        break;
                }
            }
        });
    }

    private void changeFragment(BaseFragment toFragment) {
        this.baseFragment = toFragment ;

        ProgressUtils.showProgress(mActivity);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                transaction.replace(R.id.mFlContainer ,toFragment);
                transaction.commitAllowingStateLoss();
            }
        } , 200);
    }

    @Override
    protected void initMessage(MessageSocketBean messageSocketBean) {
        if(isShowMessageDialog)
            showMessageDialog(messageSocketBean);
    }

    @Override
    protected void initRefresh(int count) {
        if(baseFragment != null)
            baseFragment.initConnect();
    }

    public void onClickNull(View view){
        if(baseFragment != null) {
            ProgressUtils.showProgress(mActivity);
            baseFragment.initConnect();
        }
    }

    @Override
    public void onBackPressed() {
        if(Constant.MODEL_NW.equals(Build.MODEL)){
            if(IsOpenDrawer)
                onBackDoubleClick();
        }else {
            if(IsOpenDrawer){
                mDlContainer.closeDrawers();
            }else {
                onBackDoubleClick();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;

        switch (v.getId()){
            case R.id.mIbVersionUpdate :
                // 更新
                showUpdateShow();
                break;
            case R.id.mLlMessage:
                // 消息
                MessageDialog.getInstance(mActivity)
                        .show();
                break;
        }
    }

    private boolean IsOpenDrawer ;

    /**
     * 监听抽屉变动
     */
    private MainDrawerListener mDrawerListener = new MainDrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull @NotNull View drawerView, float slideOffset) {
            mViewLeftLine.setVisibility(slideOffset == 0 ? View.VISIBLE : View.GONE);
        }

        @Override
        public void onDrawerClosed(@NonNull @NotNull View drawerView) {
            IsOpenDrawer = false;
        }

        @Override
        public void onDrawerOpened(@NonNull @NotNull View drawerView) {
            IsOpenDrawer = true;
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == mActivity.RESULT_OK && requestCode == Constant.REQUEST_CODE && data != null){
            HmsScan hmsScan = data.getParcelableExtra(ScanUtil.RESULT);
            if(baseFragment != null)
                baseFragment.onScanResult(hmsScan.originalValue);
        }
    }

    /**
     * 初始化光学扫描
     */
    private void initM5Optics(){
        Intent scanIntent = new Intent(Constant.M5_Scan_Start_Service);
        scanIntent.putExtra(Constant.Poc_Key, Constant.Enable);
        scanIntent.putExtra(Constant.Ptt_Key, Constant.Enable);
        sendBroadcast(scanIntent);

        m5ScanReceiver = new M5ScanReceiver();
        IntentFilter mM5ScanFilter = new IntentFilter();
        mM5ScanFilter.addAction(Constant.M5_Scan_Result);
        mM5ScanFilter.addAction(Constant.M5_Click_Poc);
        mM5ScanFilter.addAction(Constant.M5_Click_Ptt);
        registerReceiver(m5ScanReceiver, mM5ScanFilter);
    }

    /**
     * 监听M5光学扫描
     */
    private M5ScanReceiver m5ScanReceiver ;

    private class M5ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(Constant.M5_Scan_Result)){
                // 扫描结果回调
                if(baseFragment != null)
                    baseFragment.onScanResult(intent.getExtras().get(Constant.RESULT).toString());
            } else if(action.equals(Constant.M5_Click_Poc) || action.equals(Constant.M5_Click_Ptt)){
                // 按键监听
                sendBroadcast(new Intent(Constant.M5_Scan_Start_Scan));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isShowMessageDialog = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isShowMessageDialog = false;
    }

    @Override
    protected void onDestroy() {
        // 关闭消息服务
        if(mMessageService != null)
            stopService(mMessageService);
        if(mRefreshService != null)
            stopService(mRefreshService);

        if(Constant.MODEL_M5.equals(Build.MODEL)) {
            sendBroadcast(new Intent(Constant.M5_Scan_Stop_Service));
            if (m5ScanReceiver != null)
                unregisterReceiver(m5ScanReceiver);
        }
        super.onDestroy();
    }
}